import { Component, Vue } from "vue-property-decorator";
import { ModalDialog } from "@/utils/modal-dialog.ts";
import { FormulaService } from "@/services/formula-service";
import "../../../public/marvinjs/js/marvinjslauncher.js";
import { ReactionEditor } from "@/components/reaction-editor/reaction-editor";
import { Constant } from "@/constant";

@Component({
  props: {
    format: {
      type: String,
      required: true
    },
    isReaction: {
      type: Boolean,
      default: true
    },
    value: {
      type: String
    },
    zoomable: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    format: function() {
      this.createImage();
    },
    isReaction: function() {
      this.createImage();
    },
    value: function() {
      this.createImage();
    }
  },
  components: {
    ReactionEditor
  }
})
export class StructureViewer extends Vue {
  private marvin = null;
  private zoomableModalVisible: boolean = false;
  private sketch: any = null;

  sketchChange(sketch) {
    this.sketch = sketch;
  }

  mounted() {
    this.createImage();
  }

  createImage() {
    window["MarvinJSUtil"].getPackage("#marvinjs-iframe").then(
      marvinNameSpace => {
        // the reference to the namespace is arrived but there is no guaranty that its initalization has been finished
        // because of it, wait till the ready state to be sure the whole API is available
        marvinNameSpace.onReady(async () => {
          this.marvin = marvinNameSpace;
          this.$refs.structureContainer["innerHTML"] = this.$props.value
            ? await FormulaService.toImage(
                this.marvin,
                this.$props.format,
                this.$props.value,
                this.$props.isReaction
                  ? Constant.MOLECULE_SIZE * 2 + Constant.LEVEL_SEPARATION
                  : Constant.MOLECULE_SIZE,
                Constant.MOLECULE_SIZE
              )
            : "";
        });
      },
      function(error) {
        ModalDialog.showError("notFound", error);
      }
    );
  }

  download() {
    this.$emit("download");
  }
}

export default StructureViewer;
